<script lang="ts" setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import conf from "@/conf/conf";
import type { ComponentSize, TableInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDetailStore } from "@/store/detail.js";
import { useRouter } from "vue-router";
import {
  Plus,
  Download,
  DocumentAdd,
  DocumentCopy,
  Search,
  RefreshRight,
} from "@element-plus/icons-vue";

const router = useRouter();

// 定义表格的实例
const tableRef = ref<TableInstance>();
// 定义接口
interface User {
  name: string;
  idCardNumber: string;
  educationLevel: string;
  politicalStatus: string;
  nativePlace: string;
  graduationDate: string;
  studentNumber: string;
  faculty: string;
  major: string;
  transferUnitName: string;
  archiveNumber: string;
  transferType: string;
  expressNumber: string;
  transferDate: string;
  id: number;
}

// 表格数据
const tableData = ref<User[]>([]);

//搜索功能的变量
const month = ref(""); // 用于存储月份
const name = ref(""); // 用于存储姓名
const educationLevel = ref(""); // 用于存储资格
const faculty = ref(""); // 用于存储学院
const totalData = ref(100); // 用于存储总数据量
const pageNum = ref(1); // 用于存储当前页码
const pageSize = ref(10); // 用于存储每页显示的条目数
const parentBorder = ref(true); // 用于控制父元素的边框
const selectedArray = ref([]); // 用于存储选中的多行数据

// 表格的变量
const size = ref<ComponentSize>("default"); // 用于存储组件大小
const selectedRows = ref([]); // 用于存储选中的多行数据

onMounted(() => {
  //发起请求
  getMessages();
});

// 获取表格数据的函数
const getMessages = (dateStr: string = "") => {
  axios({
    url: conf.url + "/archive",
    params: {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      name: name.value,
      educationLevel: educationLevel.value,
      faculty: faculty.value,
      graduationDate: dateStr,
    },
    method: "GET",
  })
    .then((res) => {
      tableData.value = res.data.data.items;
      totalData.value = res.data.data.total;
    })
    .catch((err) => {
      console.log(err);
    });
};
//选中数据操作
const handleSelectionChange = (val: Array<User>) => {
  selectedRows.value = val;
  val.forEach((item) => {
    if (!selectedArray.value.includes(item)) {
      selectedArray.value.push(item);
    }
  });
};

// 切换页面大小时触发的处理函数
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  // 重置选中数组
  selectedArray.value = [];
  selectedRows.value = [];
  tableRef.value!.clearSelection();
  getMessages();
  console.log(`每页${val}条数据`);
};

// 切换当前页面时触发的处理函数
const handleCurrentChange = (val: number) => {
  pageNum.value = val;
  getMessages();
  console.log(`当前页: ${val}`);
};

// 搜索数据的异步函数
const search = () => {
  //转换日期数据格式
  let dateStr = "";
  if (month.value) {
    let date = new Date(month.value);
    dateStr = date.getFullYear() + "" || "";
    if (date.getMonth() + 1 < 10) {
      dateStr += "0" + (date.getMonth() + 1);
    } else {
      dateStr += date.getMonth() + 1;
    }
  }
  console.log(
    `搜索条件： 姓名：【${name.value}】  学历：【${educationLevel.value}】 学院： 【${faculty.value}】 毕业日期：【${dateStr}】`
  );

  //发起请求
  getMessages(dateStr);
};

// 重置输入框的函数
const reset = () => {
  month.value = "";
  name.value = "";
  educationLevel.value = "";
  faculty.value = "";
  ElMessage({
    type: "success",
    message: "重置成功"
  })
  console.log("重置查询条件");

  getMessages();
};

// Excel导出的函数
const result = () => {
  // 导出选中的数据
  let array = [];
  if (selectedArray.value.length !== 0) {
    console.log(selectedArray.value);
  }
  selectedArray.value.forEach((item) => {
    array.push(item.id);
  });
  if (array.length === 0) {
    ElMessage({
      type: "error",
      message: "请选择数据",
    });
    return;
  }
  console.log("打印数据：");
  console.log(selectedArray.value);
  axios({
    url: conf.url + "/archive/export",
    method: "POST",
    data: array,
    responseType: "blob",
  })
    .then((res) => {
      if (res.status === 200) {
        ElMessage({
          type: "success",
          message: "导出成功",
        });
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", "学生信息.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 从文档中移除链接
        URL.revokeObjectURL(url);
        tableRef.value.clearSelection();
        selectedArray.value = [];
        selectedRows.value = [];
      } else {
        ElMessage({
          type: "error",
          message: "导出失败",
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

// 显示详细信息的函数
const detail = (row: any) => {
  console.log(row.row.id);
  useDetailStore().setDetailId(row.row.id);
  router.push("/detail");
};

// 删除选中的数据
const deleteConfirm = (id: number) => {
  let password = "";
  ElMessageBox.prompt("请输入密码以确认删除", "确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /^[a-zA-Z0-9]+/,
    inputErrorMessage: "请输入正确密码",
  })
    .then(({ value }) => {
      axios({
        url: conf.url + '/pwd',
        method: 'get'
      }).then((res) => { 
        console.log(res.data);
        password = res.data.data;
        if (value === password) {
        ElMessage({
          type: "success",
          message: `删除成功`,
        });
        deleteOne(id);
        return true;
      } else {
        ElMessage({
          type: "error",
          message: `密码错误`,
        });
        console.log(`输入的密码：${value}，正确密码：${conf.password}`);
        return false;
      }
      }).catch((err) => {
        console.log(err);
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
      return false;
    });
};

// 删除单条记录的异步函数
const deleteOne = (id: number) => {
  axios({
    url: conf.url + "/archive",
    method: "DELETE",
    params: {
      id: id,
    },
  })
    .then(() => {
      getMessages();
    })
    .catch((err) => {
      console.log(err);
    });
  tableData.value = tableData.value.filter((item: User) => item.id !== id);
};

// 重置筛选条件的函数
const resetFilter = () => {
  tableRef.value!.clearFilter();
};

// 过滤函数
const filterPoliticsStatus = (value: string, row: any) => {
  return row.politicalStatus === value;
};

// 过滤函数
const filterDegreeStatus = (value: string, row: any) => {
  return row.educationLevel === value;
};
//选中本页全部数据
const selectAll = (rows: User[]) => {
  console.log(rows);
  console.log(rows.length);
  selectedArray.value = rows;
};
const getRowKeys = (row) => {
  //记录每行的key值
  return row.id;
};

// 导出全部数据的函数
const outputAll = () => {
  let array = [];
   let dateStr = "";
  if (month.value) {
    let date = new Date(month.value);
    dateStr = date.getFullYear() + "" || "";
    if (date.getMonth() + 1 < 10) {
      dateStr += "0" + (date.getMonth() + 1);
    } else {
      dateStr += date.getMonth() + 1;
    }
  }
  axios({
    url: conf.url + "/archive",
    method: "GET",
    params: {
      pageNum: 1,
      pageSize: totalData.value,
      name: name.value,
      educationLevel: educationLevel.value,
      faculty: faculty.value,
      graduationDate: dateStr,

    }
  }).then((res) => {
    array = res.data.data.items.map((item) => item.id);
    console.log(array);
        ElMessage({
      type: "success",
      message: "加载成功,正在导出,请稍后..",
    });
    axios({
    url: conf.url + '/archive/export',
    method: "POST",
    data: array,
    responseType: "blob",
  }).then((res) => {
      if (res.status === 200) {
        ElMessage({
          type: "success",
          message: "导出成功",
        });
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", "学生信息.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 从文档中移除链接
        URL.revokeObjectURL(url);
        tableRef.value.clearSelection();
        selectedArray.value = [];
        selectedRows.value = [];
      } else {
        ElMessage({
          type: "error",
          message: "导出失败",
        });
      }
  }).catch((err) => {
      console.log(err);
  });
  }).catch((err) => {
    console.log(err);
  });
  
}
</script>
<template>
  <!-- 这是一个表单，用于输入和查询学生信息 -->
  <div class="container ep-bg-purple">
    <el-row>
      <el-col :span="3">
        <div class="grid-content">
          <span>姓名：</span>
          <el-input
            v-model="name"
            style="width: 6rem"
            placeholder="请输入姓名"
          />
        </div>
      </el-col>
      <el-col :span="3">
        <div class="grid-content">
          <span>学历：</span>
          <el-input
            v-model="educationLevel"
            style="width: 6rem"
            placeholder="请输入学历"
          />
        </div>
      </el-col>
      <el-col :span="3">
        <div class="grid-content">
          <span>学院：</span>
          <el-input
            v-model="faculty"
            style="width: 6rem"
            placeholder="请输入学院"
          />
        </div>
      </el-col>
      <el-col :span="5">
        <div class="grid-content">
          <span>毕业年月：</span>
          <el-date-picker
            v-model="month"
            type="month"
            placeholder="请选择毕业年月"
            style="width: 9rem"
          />
        </div>
      </el-col>
      <el-button-group class="BG">
        <el-button type="danger" @click="search" round color="#3498db">
          <el-icon><Search color="white" /></el-icon>
          <span class="el-icon-text">搜索</span>
        </el-button>
        <el-button type="warning" @click="reset" color="#e74c3c">
          <el-icon><RefreshRight color="white" /></el-icon>
          <span class="el-icon-text">重置</span>
        </el-button>
        <el-button type="success" color="#2ecc71" @click="$router.push('/add')">
          <el-icon><Plus color="white" /></el-icon>
          <span class="el-icon-text">添加</span>
        </el-button>
        <el-button type="success" color="#27ae60" @click="$router.push('/multipleUpload')">
          <el-icon><DocumentAdd color="white" /></el-icon>
          <span class="el-icon-text">批量添加</span>
        </el-button>
        <el-button type="primary" color="#FEc40f" @click="result">
          <el-icon><Download color="white" /></el-icon>
          <span class="el-icon-text">导出</span>
        </el-button>
        <el-button type="primary" color="#f39c12" round @click="outputAll">
          <el-icon><DocumentCopy color="white" /></el-icon>
          <span class="el-icon-text">全部导出</span>
        </el-button>
      </el-button-group>
    </el-row>
  </div>
  <!-- 数据表格，用于显示查询结果 -->
  <div class="table-container">
    <span style="margin-left: 20px">
      显示边框: <el-switch v-model="parentBorder" />
    </span>
    <span style="margin-left: 20px">
      <el-button @click="resetFilter" style="height: 25px">重置筛选</el-button>
    </span>
    <el-table
      :data="tableData"
      style="width: 100%"
      stripe
      height="500"
      @select="handleSelectionChange"
      :border="parentBorder"
      :row-key="getRowKeys"
      ref="tableRef"
      :select-on-indeterminate="true"
      @select-all="selectAll"
    >
      <el-table-column
        fixed
        type="selection"
        min-width="40"
        v-model="selectedRows"
        :reserve-selection="true"
        align="center"
      />
      <el-table-column
        prop="name"
        label="姓名"
        min-width="75"
        fixed
        align="center"
      />
       <el-table-column
        prop="studentNumber"
        label="学号"
        align="center"
        min-width="130"
      />
      <el-table-column
        prop="educationLevel"
        label="学历"
        align="center"
        min-width="100"
        :filters="[
          { text: '本科', value: '本科' },
          { text: '硕士', value: '硕士' },
          { text: '博士', value: '博士' },
          { text: '其他', value: '' },
        ]"
        :filter-method="filterDegreeStatus"
      />
      <el-table-column prop="faculty" label="院系" width="160" align="center" />
      <el-table-column
        prop="major"
        label="专业"
        min-width="180"
        align="center"
      />
      <el-table-column
        prop="politicalStatus"
        label="政治面貌"
        min-width="95"
        align="center"
        :filters="[
          { text: '群众', value: '群众' },
          { text: '共青团员', value: '共青团员' },
          { text: '中共党员', value: '中共党员' },
          { text: '其他', value: '' },
        ]"
        :filter-method="filterPoliticsStatus"
      />
      
      <el-table-column
        prop="nativePlace"
        label="生源所在地"
        align="center"
        min-width="150"
        max-width="300"
      />
     
      <el-table-column
        prop="graduationDate"
        label="毕业时间"
        sortable
        align="center"
        min-width="110"
      />
      <el-table-column fixed="right" label="操作" width="120" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="detail(scope)">
            详情
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="deleteConfirm(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页组件，用于控制表格数据的分页显示 -->
  <div class="demo-pagination-block">
    <el-pagination
      background
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      paper-count="5"
      :size="size"
      :default-page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalData"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="justify-content: center; align-items: center; margin-top: 5px"
      hidden-on-single-page
    />
  </div>
</template>

<style scoped>
@import "@/assets/css/selectPage.css";
</style>